<template>
	<scroll-view class="container" scroll-y @scroll="handleScroll">
		<!-- 固定头部 -->
		<view class="fixed-header">
			<view class="hede">
				<view class="toback">
					<uv-icon name="arrow-left" color="#333" size="18" @click="back" />
				</view>
				<view class="search">
					<uv-search v-model="keyword" bgColor="#F4F5F7" :showAction='false' placeholder="搜索订单"
						placeholderColor="#B1B1B1" @search="onSearch" @clear="onSearch" />
				</view>
				<uv-tabs :list="tabslist" @click="tabsClick" lineColor="#BC2722" lineWidth="30"
					activeStyle="color: #000;font-weight: bold;" />
			</view>
			<view class="pingjia" v-if="tabsIndex === 4">
				<view @click="comment(1)" style="position: relative;" :class="{'cur':evaluation_status==1}">待评价
					{{to_be_evaluated>0?to_be_evaluated:''}}
				</view>
				<view @click="comment(2)" style="position: relative;" :class="{'cur':evaluation_status==2}">已评价
					{{evaluated_num>0?evaluated_num:''}}
				</view>
			</view>
		</view>
		<!-- 可滚动内容 -->
		<view :class="tabsIndex==4?'pd_pj':'pd_npj'">
			<commentList :list="list" @btnRefresh="refresh" v-if="status==4 && evaluation_status==2" />
			<ListPage :list="list" @btnClick="btnClick" v-else />
			<uv-gap height="20" bgColor="transparent" />
		</view>
	</scroll-view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		onBeforeUnmount,
		computed,
		nextTick
	} from 'vue';
	import {
		getIconPath
	} from '@/util'
	import ListPage from './order_list.vue'
	import commentList from './comment_list.vue'
	import {
		onLoad,
		onReachBottom,
		onShow,
		onPullDownRefresh
	} from '@dcloudio/uni-app'
	import {
		getPaymentMethod,
		getMarketOrderList,
		getCommnetNum,
		getEvaluatedList,
		cancelMarketOrder,
		delMarketOrder,
		receiveGoods,
		payOrder
	} from '@/api'
	import {
		backToTargetPage
	} from '@/util/tools'
	import {
		useRefreshStore,
		userefundStore,
		useCommnetStore,
		useTabbarStore
	} from '@/store'
	const refreshStore = useRefreshStore()
	const tabbarStore = useTabbarStore()
	const tabbarActive = computed(() => tabbarStore.active)
	const refund = userefundStore()
	const commentStore = useCommnetStore()
	const keyword = ref('')
	const page = ref(1)
	const list = ref([])
	const total = ref(0)
	const status = ref(0)
	const evaluation_status = ref(1)
	const to_be_evaluated = ref(0)
	const evaluated_num = ref(0)
	const finished = ref(false)
	const tabsIndex = ref(0)
	const tabslist = ref([{
			name: '全部'
		}, {
			name: '待付款'
		}, {
			name: '待发货'
		},
		{
			name: '待收货'
		}, {
			name: '评价'
		}, {
			name: '退款/售后'
		}
	])
	const statusList = ref([0, 1, 2, 3, 4, 6])
	const order_id = ref(0)
	const back = () => {
		backToTargetPage('pages/home/index')
	}
	const getList = async () => {
		finished.value = false;
		if (page.value === 1) list.value = []
		let params = {
			page: page.value,
			limit: 10,
			status: status.value,
			order_no: keyword.value
		}
		if (status.value == 4) {
			params.evaluation_status = evaluation_status.value
			let res = (await getCommnetNum({order_no:keyword.value})).result
			to_be_evaluated.value = res.to_be_evaluated
			evaluated_num.value = res.evaluated_num
		}
		if (status.value == 4 && evaluation_status.value == 2) {
			const {
				result
			} = await getEvaluatedList(params)
			page.value++
			total.value = result.total
			list.value = [...list.value, ...result.data]
			finished.value = list.value.length >= result.total;
		} else {
			const {
				result
			} = await getMarketOrderList(params)
			page.value++
			total.value = result.total
			list.value = [...list.value, ...result.data]
			finished.value = list.value.length >= result.total;
		}
	}
	let isRefreshing = false;
	const tabsClick = async (e) => {
		if (isRefreshing) return;
		isRefreshing = true;
		if (e) {
			tabsIndex.value = e.index
			status.value = statusList.value[e.index]
		}
		uni.showLoading({
			title: '加载中',
			mask: true
		});
		page.value = 1;
		list.value = []; // 清空旧数据
		await getList(); // 确保数据加载完成
		uni.hideLoading();
		isRefreshing = false;
	}
	const scrollTop = ref(0)
	const isAtTop = ref(true)
	const handleScroll = (e) => {
		// 判断是否在顶部
		isAtTop.value = e.detail.scrollTop <= 10
		// 如果需要，可以在这里添加其他滚动处理逻辑
		//console.log('当前滚动位置:', e.detail.scrollTop)
	}
	onPullDownRefresh(() => {
		// 只有在顶部时才执行刷新
		if (isAtTop.value && tabbarActive.value == 2) {
			tabsClick();
			setTimeout(() => {
				uni.stopPullDownRefresh();
			}, 1000);
		} else {
			// 不在顶部时立即停止刷新
			uni.stopPullDownRefresh();
		}
	})
	const onSearch = async () => {
		await tabsClick();
	}
	const popupSelect = (e) => {
		console.log(e);
	}
	const comment = (e) => {
		evaluation_status.value = e
		page.value = 1
		list.value = []
		getList()
	}
	onReachBottom(() => {
		if (tabbarActive.value == 2) {
			if (finished.value) return
			getList()
		}
	})
	const btnClick = async ({
		type,
		i,
		j
	}) => {
		if (type === 1) {
			uni.navigateTo({
				url: '/pages-home/market/order_detail?order_id=' + list.value[i].order_id +
					'&merchant_order_id=' + list.value[i].id
			})
		} else if (type === 2) {
			uni.showModal({
				title: '提示',
				content: '确定取消订单吗？',
				success: async (res) => {
					if (res.confirm) {
						let result = await cancelMarketOrder({
							order_id: list.value[i].order_id,
							merchant_order_id: list.value[i].id
						})
						if (result.code == 200) {
							tabsClick()
							uni.showToast({
								title: '取消订单成功',
								icon: 'none'
							})
						} else {
							uni.showToast({
								title: result.msg,
								icon: 'none'
							})
						}
					}
				}
			})
		} else if (type === 3) {
			uni.showModal({
				title: '提示',
				content: '确定删除订单吗？',
				success: async (res) => {
					if (res.confirm) {
						let result = await delMarketOrder({
							order_id: list.value[i].order_id,
							merchant_order_id: list.value[i].id
						})
						if (result.code == 200) {
							tabsClick()
							uni.showToast({
								title: '删除订单成功',
								icon: 'none'
							})
						} else {
							uni.showToast({
								title: result.msg,
								icon: 'none'
							})
						}
					}
				}
			})
		} else if (type === 4) {
			uni.navigateTo({
				url: '/pages-home/market/goods_topay?order_id=' + list.value[i].order_id +
					'&merchant_order_id=' + list.value[i].id
			})
		} else if (type === 5) {
			//申请退款
			let product = list.value[i].order_info[j];
			refund.setRefundData(product)
			uni.navigateTo({
				url: '/pages-home/market/refund'
			})
		} else if (type === 6) {
			//查看物流
			uni.navigateTo({
				url: '/pages-home/market/logistics?order_id=' + list.value[i].order_id +
					'&merchant_order_id=' + list.value[i].id
			})
		} else if (type === 7) {
			//确认收货
			uni.showModal({
				title: '提示',
				content: '确定已收到货吗？',
				success: async (res) => {
					if (res.confirm) {
						let result = await receiveGoods({
							order_id: list.value[i].order_id,
							merchant_order_id: list.value[i].id
						})
						if (result.code == 200) {
							tabsClick()
							uni.showToast({
								title: '收货成功',
								icon: 'none'
							})
						} else {
							uni.showToast({
								title: result.msg,
								icon: 'none'
							})
						}
					}
				}
			})
		} else if (type === 8) {
			//评价
			let order = list.value[i].order_info;
			let comment_product = {
				"order_id": list.value[i].order_id,
				"merchant_order_id": list.value[i].id,
				"product": [],
				"is_anonymous": 0
			};
			for (let j = 0; j < order.length; j++) {
				if (order[j].after_sales_id > 0) {
					continue;
				}
				comment_product.product.push({
					"product_id": order[j].product_id,
					"sku_id": order[j].sku_id,
					"product_image": order[j].product_image,
					"star_rating": 0,
					"content": "",
					"image": [],
					"video": ""
				})
			}
			commentStore.setCommentData(comment_product)
			uni.navigateTo({
				url: '/pages-home/market/comment'
			})
		} else if (type === 9) {
			//售后详情
			let order_info_id = list.value[i].order_info[j].id
			if (list.value[i].order_info[j].apply_for_type == 1 && list.value[i].order_info[j].after_sales_status == 2 && list.value[i].order_info[j].refund_express == ''){
				uni.navigateTo({
					url: '/pages-home/market/refund_form?order_info_id=' + order_info_id
				})
			} else {
				uni.navigateTo({
					url: '/pages-home/market/ass_info?order_info_id=' + order_info_id
				})
			}
		}
	}
	const refresh = (flag) => {
		if (flag == 1) {
			page.value = 1;
			list.value = [];
			getList()
		}
	}
	onMounted(() => {
		getList()
	});
	onShow(async () => {
		if (refreshStore.shouldRefresh) {
			tabsIndex.value = refreshStore.refreshParams?.current || tabsIndex.value
			status.value = statusList.value[tabsIndex.value]
			evaluation_status.value = refreshStore.refreshParams?.evaluation_status || evaluation_status.value
			refreshStore.resetRefresh()
			await tabsClick()
		}
	});

	onBeforeUnmount(() => {
		refreshStore.resetRefresh()
	})
</script>

<style lang="scss" scoped>
	.container {
		background-color: #f7f7f7;
		position: relative;
		height: 94vh;
		/* #ifdef MP-WEIXIN */
		height: calc(100% - 200px); 
		/* #endif  */
	}

	.fixed-header {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 100;
		background-color: #fff;
	}
	
	.pd_pj{
		padding-top: 160px;
		/* #ifdef MP-WEIXIN */
		padding-top: 200px;
		/* #endif  */
	}
	
	.pd_npj {
		padding-top: 120px;
		/* #ifdef MP-WEIXIN */
		padding-top: 160px;
		/* #endif  */
	}

	/* 其他原有样式保持不变 */
	.hede {
		padding-top: calc(var(--status-bar-height) + 80upx);
		/* #ifdef MP-WEIXIN */
		padding-top: calc(var(--status-bar-height) + 110upx);
		/* #endif  */
	}

	.toback {
		position: absolute;
		left: 30upx;
		top: 30upx;
		/* #ifdef MP-WEIXIN */
		top: 100upx;
		/* #endif  */
	}

	.search {
		margin: 0 30upx;
	}

	.pingjia {
		display: flex;
		padding: 20upx;
		align-items: center;
		justify-content: space-between;
		background-color: #fff;
		font-size: 28upx;
		color: #727171;

		.cur {
			color: #333;
			font-weight: bold;
		}

		.cur::after {
			content: "";
			position: absolute;
			bottom: -10px;
			width: 60%;
			left: 20%;
			z-index: 999;
			height: 3px;
			background-color: #BC2722;
			border-radius: 3px;
		}
	}
</style>